Skip to content

fix(durable): replay an actor's done data and errors as the live run delivered them - #268

Merged
reka18 merged 11 commits into
mainfrom
fix/durable-actor-outcome-replay
Nov 24, 2026
Merged

reka18 merged 11 commits into
mainfrom
fix/durable-actor-outcome-replay

Conversation

@reka18

@reka18 reka18 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What this does

An actor's done data and errors now replay exactly as the live run delivered them. This is the same treatment #258 gives service results.

On main, the parent's onDone Assign saw the actor's own Go value live, but JSON's generic form after Recover. An Order came back as a map[string]any, and an int64 as a float64. An error with invalid UTF-8 replayed with U+FFFD. An error whose Error() panics, such as a typed nil, killed the host process: failOnPanic failed the Handle and then re-panicked.

Now:

  • Done data goes through WithEventDataDecoder for the parent's onDone event, both live and on replay. Replay holds the decoder to the Go type the live settle recorded, as feat(durable): decode service results through WithEventDataDecoder and park undecodable ones #258 does for services. WithResultTypeAlias covers a renamed done-data type the same way it covers a service result, on every replay path: Recover from the journal, Recover from a checkpoint, and StateAt.
  • Errors are message-only both live and on replay, with invalid UTF-8 replaced. An Error() that panics settles with a message saying so, rather than crashing the host.
  • Done data that won't decode aborts the settle before anything fires. The step fails the Handle with ErrEventDataEncoding and records nothing, and the actor runs again on Recover. Unlike a service result, an actor outcome is never parked, because nothing can re-settle an actor without running it again.
  • A settle that routes nothing, a success with no onDone or a failure with no onError, runs no transform and behaves exactly as on main.

New API, for the maintainer to decide

state.ActorSystem.WithSettleTransform(func(event E, output any, err error) (out any, outErr error, abort error)) *ActorSystem[S, E, C]

It's the actor counterpart of the ServiceRunner's WithResultTransform. Every actor settle passes the outcome directly to the parent's Fire, so durable has no other place to make live and replay agree. The transform runs before the actor is marked done, and only when the settle routes a completion. An abort fires nothing and leaves the actor running. It's flagged in state's changelog. I'm suggesting it, not deciding it.

Recorded done-data types

Actor entries now carry the done data's Go type, recorded the same way a service result's is. There's no journal format bump and no old-journal gate, because durable is greenfield.

Tests

  • Live and replay agree for each end: an actor driven by DeliverToActor, and actors spawned during Fire, Tick, RunService and Start, each checked against Recover and StateAt.
  • Two actors settling with distinct done data in one step each journal and replay their own.
  • A renamed done-data type replays under WithResultTypeAlias, through the journal and through a checkpoint.
  • An unrouted settle runs no transform and consults no decoder, even when its output won't encode.
  • Invalid UTF-8, and a panicking or typed-nil Error(), on both paths.
  • An undecodable settle fails each driving step.
  • state: the transform rewrites an outcome before Assign sees it. An abort fires nothing. A settle whose transform ran while the actor was stopped and respawned under the same id leaves the new actor alone.

Checks

  • go test -race, golangci-lint and govulncheck pass in state, durable, transport, e2e and examples/dispatch (go1.27.4)
  • CHANGELOG entries in state and durable

Rebased onto main after #258 and #267 merged, so it's no longer stacked.

Closes #256

@reka18 reka18 added ready All ACR dimensions confirmed - clear to merge confirmed:correctness ACR clean: correctness confirmed:regression-safety ACR clean: regression-safety confirmed:concurrency-discipline ACR clean: concurrency-discipline confirmed:replay-determinism ACR clean: replay-determinism confirmed:api-compatibility ACR clean: api-compatibility confirmed:missed-context ACR clean: missed-context confirmed:human-readability ACR clean: human-readability confirmed:probes ACR: the probes lens's latest round found no blocker labels Nov 18, 2026
@reka18

reka18 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Review findings

The AI reviewers' pass over this change checked every review label and found no blockers in durable. Four non-blockers in the new state code were real, and all four are handled in the second commit:

  1. A settle could act on a different actor respawned under the same id. The transform runs outside the lock, and settle then looked the actor up again by id only. If the actor was stopped and spawned again in the meantime, the old outcome settled the new actor. Settle now holds to the actor it started for. A deterministic test covers both the settle branch and the abort branch, and each check fails its test when removed. The durable Runner can't reach this, since its step lock serializes all driving, but ActorSystem is public.
  2. An abort from a settle that a delivery drives isn't visible to Deliver's caller. Deliver returns only a bool, so this is documented instead of changing its signature. The actor stays running, and the host sees the abort through Tick or SettleError. The durable Runner reports it through the Handle.
  3. A replay type error called an actor's done data a "service result". The message now names the outcome, and a test asserts the wording.
  4. A new helper copied IsRunning. It's replaced by the one identity check that fix 1 needs.

@reka18
reka18 force-pushed the fix/durable-actor-outcome-replay branch from e49c94b to 3687520 Compare November 18, 2026 19:33
@reka18 reka18 added not-ready On every new PR until all review dimensions are confirmed ready All ACR dimensions confirmed - clear to merge and removed ready All ACR dimensions confirmed - clear to merge not-ready On every new PR until all review dimensions are confirmed labels Nov 18, 2026
@reka18
reka18 force-pushed the fix/durable-actor-outcome-replay branch from 3687520 to 23391d7 Compare November 18, 2026 19:55
@reka18

reka18 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Decisions for Temple to ratify

I made these calls in this PR. Each is a suggestion for you to confirm or change.

  1. New exported API: state.ActorSystem.WithSettleTransform(func(event E, output any, err error) (out any, outErr error, abort error)). An actor's settle passes its outcome straight to the parent's Fire, so durable has no other place to make live and replay agree. It mirrors the ServiceRunner's WithResultTransform.
  2. Actor outcomes are never parked. Done data that won't decode fails the Handle, records nothing, and the actor runs again on Recover. Parking would need a way to settle an actor without running it again, and nothing provides one.
  3. An actor's error reaches Assign message-only, both live and on replay, the same as a service error. So errors.Is and errors.As no longer match it in onError.
  4. An abort from a settle that a delivery drives isn't reported to Deliver's caller. That's documented rather than changing Deliver's signature. The host sees it through Tick or SettleError, and the durable Runner reports it through the Handle.
  5. The journal format goes to 5, and actor outcomes from format 4 or lower replay in JSON's generic form. Since then I've decided durable is greenfield, so new fixes don't bump the format for older journals. If you agree, this bump and feat(durable): decode service results through WithEventDataDecoder and park undecodable ones #258's format 4 could be dropped.

@reka18
reka18 force-pushed the feat/durable-service-result-decoder branch 2 times, most recently from 6d3453d to 889d948 Compare November 19, 2026 17:04
Base automatically changed from feat/durable-service-result-decoder to main November 23, 2026 17:28
…delivered them

An actor's done data reached the parent as the behavior's own Go value on
the live run and as JSON's generic form on replay, so a parent reducer saw
two shapes for one transition (#256): an order live, a map after Recover.
An actor's error kept its raw message live and the U+FFFD-replaced one a
Store keeps on replay, and an error whose Error method panics — a typed
nil, which a host's own ActorInstance can settle with — crashed the host
through the journal's Error() call.

- state: ActorSystem.WithSettleTransform rewrites every actor outcome
  before it settles, whether a delivery, a panic the actor raised while
  stepping, or SettleError settles it, mirroring
  ServiceRunner.WithResultTransform: it gets the event that will carry the
  outcome and runs before the actor is marked done and before the routing
  Fire. A non-nil abort fires nothing and leaves the actor running,
  reported as the ServiceRunner's abort is.
- durable: the Runner settles its actors through the transform the service
  seam uses (#258's replayableOutcome, generalized to name its outcome), so
  an actor's done data decodes through WithEventDataDecoder for the
  parent's onDone event, live as on replay; an error is message-only,
  normalized; and one whose Error method panics settles with a message
  saying so. The journal records the JSON the live settle decoded with the
  done data's Go type, in actor entries, and replay holds the decoder to
  that type, as a recorded service result's replay does.
- durable: there is no parking for an actor outcome, as a service result
  that won't decode has. Done data that won't decode, or decodes as
  another type than the actor produced, aborts the settle, fires nothing,
  and fails the Handle — the delivery, or the Fire, Tick or RunService
  whose absorb drove the settle — recording nothing, so the actor runs
  again on Recover. Start and Recover fail the same way when a settle
  their spawns drive aborts.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
…eliver's abort

A settle whose WithSettleTransform function ran while the actor was
stopped and spawned again under the same id settled the new actor with the
old outcome, or reported its abort as though the new actor were the
one the transform ran for. The settle now holds to the *runningActor it
began for, still running: when the actor under the id is another one it
returns false, fires nothing, and reports no abort, leaving the new
actor running, as the ServiceRunner's stale settle does for a re-armed
activation. A deterministic test drives the respawn from inside the
transform — the supervisor leaves supervising and re-enters it, which
stops the child and spawns a fresh one under the same id — and
mutation-checks both branches: dropping either identity check fails it.

- state: Deliver's and WithSettleTransform's documentation now say an
  abort from a settle a delivery drives isn't reported to Deliver's
  caller: Deliver returns only whether it found the actor running, so
  the actor stays running and the host sees the abort by calling Tick
  or SettleError itself; the durable Runner reports it through the
  Handle.
- durable: the type check a replay holds a recorded outcome to
  (decodedAsRecorded) now takes the outcome's name the way
  decodedAsPassed does, so an actor's done-data a Recover's decoder
  returns as another type fails saying "actor done-data", not "service
  result".

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
An actor's done-data is held to the Go type the live settle recorded,
so the rename concern WithResultTypeAlias answers for service results
applies to it: a pure refactor that moves or renames the type failed
Recover and StateAt for every journal already settled under the old
name, with no way to tell the Runner what the recorded name now means.

The alias now covers actor done-data on every replay path — Recover
from the journal, Recover from a checkpoint's tail, and StateAt —
through the same replayableOutcome transform the live settle and a
recorded service result's replay use, with no new exported API: the
option's doc comment now says it covers both outcomes. A decoder that
returns the aliased type settles the done-data, and every other
recorded name is held to strictly, exactly as before. The refusal
wording matches a recorded service result's, naming the done-data and,
when an alias covers the name, the aliased type to decode as.

Tests cover Recover and StateAt from the journal and a Recover from a
checkpoint whose compacted tail holds the settle, in the style of
TestResultTypeAlias_RenamedSettledResult, and are mutation-checked:
dropping the alias lookup on the actor path fails them.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
…ill in the review's docs and probe

The settle transform ran for every settle, routed or not, so an actor
spawned with no onDone for its outcome — a dynamic spawn; an invoked
actor always routes, firing the zero event its unset outcome leaves —
whose Output() won't encode aborted a settle that would otherwise have
been the fire-and-forget no-op it is without the transform, failing the
delivery's Handle for an outcome nothing consumes. The transform now
runs only when the settle routes a completion, to the invocation's
onDone for a success or its onError for a failure; a settle that routes
nothing runs no transform, aborts nothing, fires nothing, journals
nothing, and LastOutput and LastError keep the raw outcome, exactly as
on main. The staleness checks are unchanged.

The docs claimed a host could see a delivery-driven abort by calling
Tick after it; it can't, because the delivery drained the mailbox, so
that Tick returns early. The Deliver doc, the WithSettleTransform doc
and state's CHANGELOG now say the abort is never recoverable through
Deliver: it's visible only to a host that drives Tick itself, or
through SettleError, and the durable Runner's Handle, which reports it,
is the intended channel. WithEventDataDecoder's doc gains the actor
done-data paragraph its README and doc.go already carry, and durable's
actor docs note the unrouted rule.

New tests pin the unrouted settle as a no-op in state — no transform
call for an output that won't encode, for the zero event an onDone-less
settle would hand a decoder that refuses it, or for a failure, which
escalates as without the transform — and through durable, where the
channeled output settles without failing the Handle and Recover and
StateAt replay the run, and a decoder that refuses the zero event is
never consulted. A probe drives one Fire whose absorb finishes two
actors with distinct done data and asserts each journal entry's Data
and Type and each onDone Assign's value, live, after Recover and
through StateAt, catching a swapped or dropped settle relay. Both are
mutation-checked: the transform back ahead of the route check turns
the unrouted tests red, and a one-behind settle slot turns the probe
red.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
@reka18
reka18 force-pushed the fix/durable-actor-outcome-replay branch from 23391d7 to 681f0ef Compare November 23, 2026 18:42
@reka18

reka18 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Decisions for Temple to ratify

I made these calls in this PR. Each is a suggestion for you to confirm or change.

  1. WithSettleTransform is new state API. It's the actor counterpart of WithResultTransform, and the only place durable can make live and replay agree, because a settle goes straight to the parent's Fire.
  2. The transform runs only when the settle routes a completion. A success with no onDone, or a failure with no onError, runs no transform and settles as on main. Otherwise an actor whose unused output won't encode would abort, rerun on Recover, and abort again, leaving the instance stuck. The cost is that LastOutput for an unrouted settle reports the raw value.
  3. An undecodable done data fails the Handle and is never parked. A service result can be parked and settled again later, but nothing can re-settle an actor without running it again.
  4. WithResultTypeAlias covers actor done data too. It uses the same option with no new API, so a renamed type behaves the same for services and actors.

@reka18
reka18 marked this pull request as ready for review November 23, 2026 18:44

@joshua-temple joshua-temple left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium-to-critical findings, each reproduced with a probe test on this head (681f0ef). Inline comments carry the detail.

  • 1 High: service.go:285 re-runs a ServiceFn after an actor abort
  • 10 Medium: state/actor_system.go (6), durable/runner.go (2), test and CHANGELOG (2)
  • 1 stale doc outside the diff: docs/src/content/docs/durable/overview.md:168 still says a reducer observes the JSON-decoded shape on replay; the PR removed that caveat from durable/README.md and doc.go only
  • Suite is green under -race and -shuffle; the gaps are untested branches and the cases above

Comment thread state/actor_system.go Resolved
Comment thread state/actor_system.go Resolved
Comment thread state/actor_system.go Resolved
Comment thread state/actor_system.go Resolved
Comment thread state/actor_system.go Resolved
Comment thread durable/service.go Resolved
Comment thread durable/runner.go Resolved
Comment thread durable/runner.go Resolved
Comment thread durable/actor_outcome_ends_test.go Resolved
Comment thread durable/CHANGELOG.md Resolved

@joshua-temple joshua-temple left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary (medium and above only):

  • High: an InvokeActor with no onDone counts as routed (zero event), so its success now consults the decoder and can fail the Handle. It worked on main.
  • High (same root): pre-PR journals with that refused zero-event settle now fail Recover under a strict decoder.
  • Medium: WithSettleTransform aborts are dropped on the sendTo/Deliver path for any non-durable host.
  • Probe: a strict decoder plus InvokeActor("kid", WithInvokeOnError("childFail")), then DeliverToActorByID("finish"). On main it returns true, nil. On this branch it returns ErrHandleFailed (actor done-data won't decode for event : no payload expected for event "").
  • Unrouted coverage uses only the Spawn action (quietMachine, unroutedParentMachine), which leaves OnDone nil. So it skips the invoked-actor shape.
  • go test -race is green for state and durable at 681f0ef.

Comment thread state/actor_system.go Resolved
Comment thread durable/actor.go Resolved
Comment thread state/actor_system.go Resolved
@joshua-temple

Copy link
Copy Markdown
Collaborator

Test gap: please add coverage for the unrouted settle on an InvokeActor actor.

  • Current "unrouted settle" tests only use the Spawn action, which has no onDone, so they never reach the InvokeActor path.
  • Add: InvokeActor with no onDone handler, success settle, strict decoder that rejects unhandled events. Assert Handle succeeds and redelivery after Recover succeeds (matches main).
  • Add: replay of a journal written before this change (settle data with no recorded type) under a strict decoder. Assert Recover and StateAt succeed.
  • Add: WithSettleTransform abort through deliver (sendTo/sendParent/forwardTo). Assert the abort is surfaced and the actor does not stay running.
  • Each should fail on the current head, which confirms it covers the findings in the review above.

@joshua-temple

Copy link
Copy Markdown
Collaborator

Follow-up: I ran a probe test for each finding in the review above, against main and against 681f0ef. All three hold, there are no new findings, and nothing needs correcting.

1. High: an invoked actor with no onDone now fails the Handle under a strict decoder (state/actor_system.go:831)

  • main: TestZZ1 passes (DeliverToActor and the follow-up Fire both return nil).
  • 681f0ef: fails with actor done-data won't decode for event : no payload expected for event "", and the follow-up Fire returns ErrHandleFailed.

2. High: a journal written on main fails Recover on this branch (durable/actor.go:362)

  • The journal was written on main to a FileStore (ZZ_PHASE=write). Recovering it on main passes.
  • Recovering the same files on 681f0ef fails: at step 1: ... decoding recorded actor "zz:supervising:actor:0" done-data: ... won't decode for event : no payload expected for event "".
  • The PR body treats durable as greenfield with no old-journal gate, so this matters only if histories already exist.
Probe for 1 and 2: durable/zz_invoke_probe_test.go
package durable_test

import (
	"context"
	"fmt"
	"os"
	"testing"

	"github.com/stablekernel/crucible/durable"
	"github.com/stablekernel/crucible/state"
)

type zzCtx struct {
	Notes []string `json:"notes"`
}

type zzOrder struct{ ID int }

// zzChild completes with output once delivered "finish".
func zzChild(output any) state.ActorBehavior {
	return func(map[string]any) (state.ActorInstance, error) {
		child := state.ForgeFor[zzCtx]("child").
			State("working").State("done").Final().Initial("working").
			Transition("working").On("finish").GoTo("done").Quench()
		inst := child.Cast(zzCtx{}, state.WithInitialState[string]("working"))
		return state.NewActor(inst, func(*state.Instance[string, string, zzCtx]) any { return output }), nil
	}
}

// zzMachine invokes kid with an onError only: no WithInvokeOnDone.
func zzMachine() *state.Machine[string, string, zzCtx] {
	return state.ForgeFor[zzCtx]("zz").
		State("idle").
		State("supervising").InvokeActor("kid", state.WithInvokeOnError("childFail")).
		State("failed").
		Initial("idle").
		Transition("idle").On("start").GoTo("supervising").
		Transition("supervising").On("childFail").GoTo("failed").
		Transition("supervising").On("poke").GoTo("supervising").
		Quench()
}

// zzOpts wires kid and a strict decoder that knows only childFail's payload.
func zzOpts() []durable.Option[string, string, zzCtx] {
	return []durable.Option[string, string, zzCtx]{
		durable.WithActorPalette[string, string, zzCtx](map[string]state.ActorBehavior{"kid": zzChild(zzOrder{ID: 7})}),
		durable.WithEventDataDecoder[string, string, zzCtx](func(e string, data []byte) (any, error) {
			if e == "childFail" {
				return durable.DecodeAs[any](data)
			}
			return nil, fmt.Errorf("no payload expected for event %q", e)
		}),
	}
}

var zzKid = state.ActorID("zz", "supervising", 0)

// drive starts the instance, enters supervising and finishes kid; it returns the
// delivery's error and a follow-up Fire's.
func zzDrive(t *testing.T, store durable.Store, opts []durable.Option[string, string, zzCtx]) (error, error) {
	t.Helper()
	ctx := context.Background()
	h, err := durable.NewRunner(zzMachine(), store, opts...).Start(ctx, "zz", zzCtx{}, state.WithInitialState("idle"))
	if err != nil {
		t.Fatalf("Start: %v", err)
	}
	if _, err := h.Fire(ctx, "start"); err != nil {
		t.Fatalf("Fire start: %v", err)
	}
	_, derr := h.DeliverToActorByID(ctx, zzKid, "finish")
	_, ferr := h.Fire(ctx, "poke")
	return derr, ferr
}

// Finding 1: the onDone-less success of an invoked actor must not fail the Handle.
func TestZZ1_InvokedActorWithoutOnDone_StrictDecoder(t *testing.T) {
	derr, ferr := zzDrive(t, durable.NewMemStore(), zzOpts())
	if derr != nil || ferr != nil {
		t.Fatalf("DeliverToActor = %v; Fire after = %v; want both nil, as on main", derr, ferr)
	}
}

// Finding 2, phase 1 (run on main): journal the onDone-less settle to a FileStore.
// Phase 2 (run on the PR head): Recover that journal under the same strict decoder.
func TestZZ2_OldJournal_RecoverUnderStrictDecoder(t *testing.T) {
	dir := os.Getenv("ZZ_DIR")
	if dir == "" {
		t.Skip("set ZZ_DIR")
	}
	store, err := durable.NewFileStore(dir)
	if err != nil {
		t.Fatalf("NewFileStore: %v", err)
	}
	if os.Getenv("ZZ_PHASE") == "write" {
		if derr, ferr := zzDrive(t, store, zzOpts()); derr != nil || ferr != nil {
			t.Fatalf("writing the journal: %v, %v", derr, ferr)
		}
		return
	}
	if _, err := durable.Recover(context.Background(), zzMachine(), store, "zz", zzOpts()...); err != nil {
		t.Fatalf("Recover of the main-written journal = %v; want nil, as on main", err)
	}
}

Run: go test -run TestZZ1 ./durable. For 2, on main: ZZ_DIR=/some/dir ZZ_PHASE=write go test -run TestZZ2 ./durable, then on this branch: ZZ_DIR=/some/dir go test -run TestZZ2 ./durable.

3. Medium: a WithSettleTransform abort on the Deliver path reaches no caller (state/actor_system.go:1045)

  • 681f0ef: Deliver=true fired=0 parent="supervising" running=true laterTick=0 inspectorEvents=0.
  • The abort shows up in no return value, observer or inspector event. The actor stays running with an empty mailbox.
  • The new doc comment says so, so this asks for an API change (an abort observer), not a fix to a hidden bug.
Probe for 3: state/zz_abort_probe_test.go (uses settleHarness from settle_transform_test.go)
package state_test

import (
	"context"
	"errors"
	"testing"

	"github.com/stablekernel/crucible/state"
)

// Finding 3: an abort from a settle a Deliver drives reaches no caller.
func TestZZ3_SettleTransformAbort_DroppedByDeliver(t *testing.T) {
	ctx := context.Background()
	parent, sys, id := settleHarness(t, func(string, any, error) (any, error, error) {
		return nil, nil, errors.New("won't record")
	})
	var fired int
	sys.WithParentFireObserver(func(state.ParentFire[string]) { fired++ })
	var inspected []state.InspectionEvent
	sys.WithActorInspector(state.InspectorFunc(func(ev state.InspectionEvent) { inspected = append(inspected, ev) }))
	ref, _ := sys.Ref(id)
	found := sys.Deliver(ctx, ref, "finish")
	later := sys.Tick(ctx, id)
	t.Logf("Deliver=%v fired=%d parent=%q running=%v laterTick=%d inspectorEvents=%d",
		found, fired, parent.Current(), sys.IsRunning(id), len(later), len(inspected))
	if found && fired == 0 && sys.IsRunning(id) && len(later) == 0 {
		t.Fatal("the abort was dropped: Deliver reported success, nothing fired, the actor is stuck running, and a later Tick returns nothing")
	}
}

Run: go test -run TestZZ3 ./state

Candidate I ran and dropped

  • I tested done-data that won't JSON-encode. It fails the Handle without ErrEventDataEncoding on both main and this branch, so it is not a regression. This branch fails before any Assign runs, which is better than main.

…invoke declared

An InvokeActor with no WithInvokeOnDone counted as routed: invokeOutcome
boxes the zero event, so the spawn's e.OnDone.(E) always succeeded and
hasDone was true for every invoked actor. A success with no onDone then
ran the settle transform and consulted the event-data decoder for the
zero event before the parent refused it, so a strict per-event decoder
failed the Handle — DeliverToActor, Fire and Tick, live and again after
every Recover — where main journaled a refused fire and kept going. The
same held for a failure with no onError, and for a spawn that failed to
start: the zero event fired where a dynamic spawn escalates.

The invocation IR now records HasOnDone / HasOnError, set only when the
option was given, and SpawnActor carries HasDone / HasError from the
invoke options or the spawn params' presence, so the ActorSystem routes
on what was declared rather than on the zero event an unset outcome
leaves: a success with no onDone settles as the fire-and-forget no-op a
dynamic spawn's always was, and a failure or failed spawn with no
onError escalates, as a dynamic spawn's does. The Invocation fields are
additive omitempty wire fields appended to the frozen shape; services
are untouched, and a spawn that declares the zero event itself still
routes it.

Replay compat: a journal a version before this change wrote can hold a
refused settle — the zero-event settle of an onDone-less invoke — with
its done-data recorded and no type. Replay now never decodes the data of
a fire whose replay will be refused; it re-fires the recorded event
plainly and meets the same refusal, so Recover and StateAt succeed on
those histories under a strict decoder, as they did on main.

New tests pin each half: the invoked-actor unrouted settle in state (no
transform call for the undeclared outcome, success a no-op, failure
escalated, a failed spawn never caught by a zero-event transition) and
through durable (Temple's probe as a permanent test: a strict decoder,
InvokeActor with only onError, the delivery and the follow-up Fire both
healthy, live and after Recover); and the replay compat case, journal
built in-test by rewriting a record to drop the recorded type, in the
style of the alias tests' rewrite harness. All are red on the parent
commit. The two skipped #250 probes that the zero-event firing blocked
are unskipped — a failed no-onError spawn now escalates, so a transition
on the zero event never catches it and Recover retries the spawn — and
the declared-but-unroutable onError case keeps its skip with the reason
narrowed to the ErrNoTransition stopgap it actually is.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
…sorb aborts on

The High of the review's second pass: when a service's settle drove an
actor whose own settle aborted in the same step, takeAborts failed the
step and recorded nothing — including the service's own result, which
had run and decoded. Recover left the service in flight, so RunService
ran the ServiceFn again, and the abort recurred on every retry: three
attempts, three runs, non-idempotent work (a payment) repeating. That
contradicted the parking design's "never runs again" promise, which the
comment beside the check and the RunService doc both leaned on.

serviceStep now journals the service's settle — and the parent Fires the
settle's absorb drove before the abort, which applied live — before it
fails the Handle on the actor's abort. On Recover the service's settle
replays from the journal, so the ServiceFn never runs again, however
many Recover-and-retry rounds follow; only the actor re-runs, from its
initial state, on each Recover's respawn of the still-running actor and
on each redelivery. The Fire, Tick and DeliverToActor ends keep
recording nothing: no service result is theirs to lose, and re-firing
the event re-drives the actor.

The new test drives fetch's onDone into a state that spawns a poker
whose message to the parent finishes kid, whose done-data a strict
decoder refuses, and walks three Recover-and-retry rounds: the first
RunService settles fetch and fails on the aborted settle, and every
later RunService finds fetch settled in the journal and runs nothing,
while each redelivery fails on the actor alone. It is red on the parent
commit — three ServiceFn runs. The RunService row of the undecodable-
settle table is updated to the new contract, and its Fire and Tick rows
still pin recording nothing.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
…the actor one settle at a time

The Medium of the review's second pass, and the review's first-pass
concurrency finding: abort reporting was Tick-only, but Tick's results
are dropped by every delivery path — deliver, the sendTo / sendParent /
respond / forwardTo sugar through dispatch, and Deliver — so a
non-durable host on the transform got a silent abort, the actor stuck
running with a final machine and an empty mailbox, and durable knew only
through its own side channel, which noted aborts even for settles the
system then suppressed as stale.

The new ActorSystem.WithSettleAbortObserver — modeled on
WithParentFireObserver — is called once for every settle that aborts, on
every path that drives one, with a SettleAbort: the actor's id, the event
the settle would have carried the outcome through, and the abort itself.
It is the one channel a delivery's abort reaches, and the report is made
only after the settle has rechecked its actor under the system lock, so
a stale settle reports nothing. Durable wires it in place of the
transform wrapper's own noting, which simplifies parentFires.aborted and
stops noting aborts the system suppresses.

One settle now owns the actor it settles, from its entry to its return:
a settle that finds the actor already settled — SettleError on an
already-settled, not-stopped actor is refused where it re-settled on
main; that refusal gains a CHANGELOG line — or owned by a settle still
in flight, another goroutine's or the transform's own reentrant call,
returns the zero result and false, running no second transform against
the winner's outcome, so a losing concurrent settle reports nothing,
fires nothing and never overwrites the winner's recorded JSON. A Tick
whose step produced the actor's real completion waits the owner out
rather than dropping it, and a delivery whose actor is owned leaves its
envelope queued for a later Tick. The -race test drives two concurrent
settles on one id — a delivery's success and an aborting SettleError —
and the reentrancy test pins the refusal a transform's own nested settle
gets.

Two more of the review's findings ride along in settle. The respawn drop
(hearing) is now decided before the transform runs, so a settle a host's
respawn replay throws away consults no decoder and can't abort on an
outcome that differs on the respawn — Recover no longer fails for a
dropped settle whose respawned child outputs something that won't
encode. And a failure the transform rewrote into a success nothing
routes escalates the ORIGINAL error, as the failure does with no
transform: a transform may rewrite the outcome, not erase the failure —
the escalation, LastOutput and LastError all pinned by new tests, with
the UnboundActorError keep and the settled-actor refusal pinned too.

Every new test is red on the parent commit where it can be: the
vanishing failure, the respawn drop, and the observer tests (the API
itself absent); the refusal and keep tests pin behavior the parent
already had.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
The rest of the review's medium findings, as pins and doc corrections,
no behavior change:

- A panicking actor's aborted settle: Tick's panic branch returns the
  abort as its one FireResult and reports it to the observer, as the
  done branch's test already pinned — killing the two `ok ||
  res.Err != nil` mutants the review's mutation run left alive.
- Start's aborted settle: the baseline checkpoint is already written,
  so a retry Start returns ErrInstanceExists and the retry is a Recover
  from the baseline, which re-runs the spawns; the Start comment,
  doc.go and fireStep now say so, and fireStep's says an actor the
  Fire's own transition spawned isn't respawned by the Recover that
  restores the pre-event state. Both pinned: the retry-Start test
  counts the spawn runs across the attempts, and the Fire's-own-spawn
  test proves the recovered Handle doesn't run the dynamic spawn and
  re-firing the event is what runs it again.
- Panic wording pinned exactly: an actor error whose Error method
  panics settles with "actor error panicked: <recovered>", live and on
  replay, and a done-data with no JSON form fails the Handle with
  "actor done-data won't encode: <why>" — the actor seam's own words,
  so swapping them for the service seam's turns the tests red.
- The Start end's StateAt now compares its notes to the live run's, as
  the Fire, Tick and RunService ends' do, not just its error.
- durable's Changed entry on actor done-data decoding now says plainly
  what changes for callers reading AssignCtx.Event — without a decoder
  a struct arrives as a map, and errors are message-only so errors.Is
  and errors.As stop matching — and that WithEventDataDecoder is the
  opt-out. The move out of Added happened at 681f0ef; this finishes it.
- The stale line in docs/durable/overview.md that still said a reducer
  sees the JSON-decoded shape only on replay now matches the README and
  doc.go: the done-data gets the same decode live as on replay.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
@joshua-temple

Copy link
Copy Markdown
Collaborator

Medium: when a WithSettleTransform turns a failure into a success, the failure is lost when no onDone is wired (state/actor_system.go:831, and the routing that runs after the transform)

  • routed is computed from the original failure, so f runs and is handed the onError event. After f returns, settle picks the route again from the rewritten outcome: ra.onDone/ra.hasDone.
  • Probe at 681f0ef, one transform that flips every failure to ("recovered", nil, nil), three ways of wiring the actor:
    • onDone and onError wired: childDone fires and the parent reaches done. This matches the doc comment.
    • InvokeActor with only onError: the empty event fires and is refused (invalid transition ... on ""). The parent stays in supervising, with no escalation and LastError=nil.
    • Spawn with only WithSpawnOnError: nothing fires, there is no escalation, the actor is gone and LastError=nil. The failure vanishes, which breaks the rule that a child failure is never swallowed silently.
  • Reachable only through the public state API. main has no WithSettleTransform. durable can't reach it either: its wrapper always returns a non-nil error for a failure (service.go:407), and live and replay agree (TestActor_Error_* pass).
  • Suggested fix: refuse or escalate a rewrite that has no route for its new outcome. Or keep the failure on the onError route, the event f was handed.
Probe: state/zz_flip_probe_test.go (uses settleChildBehavior and trec from the package tests)
package state_test

import (
	"context"
	"errors"
	"testing"

	"github.com/stablekernel/crucible/state"
)

// flip turns every failure into a success, as WithSettleTransform's doc allows.
func flip(_ string, _ any, err error) (any, error, error) {
	if err != nil {
		return "recovered", nil, nil
	}
	return nil, nil, nil
}

func zzFlipRun(t *testing.T, name string, build func(*state.Builder[string, string, *trec]) *state.Builder[string, string, *trec], id string) {
	ctx := context.Background()
	b := state.ForgeFor[*trec](name).State("idle")
	m := build(b).
		State("done").State("failed").
		Initial("idle").
		CurrentStateFn(func(*trec) string { return "idle" }).
		Transition("supervising").On("childDone").GoTo("done").
		Transition("supervising").On("childErr").GoTo("failed").
		Quench()
	parent := m.Cast(&trec{}, state.WithInitialState[string]("idle"))
	sys := state.NewActorSystem(parent).Register("child", settleChildBehavior()).WithSettleTransform(flip)
	var fired []string
	sys.WithParentFireObserver(func(pf state.ParentFire[string]) { fired = append(fired, pf.Result.Trace.Event) })
	sys.Absorb(ctx, parent.Fire(ctx, "start").Effects)
	if id == "" {
		id = state.ActorID(name, "supervising", 0)
	}
	res, ok := sys.SettleError(ctx, id, errors.New("boom"))
	t.Logf("%s: ok=%v resErr=%v fired=%q parent=%q running=%v escalation=%v lastErr=%v",
		name, ok, res.Err, fired, parent.Current(), sys.IsRunning(id), sys.LastEscalation() != nil, sys.LastError())
}

func TestZZFlip(t *testing.T) {
	zzFlipRun(t, "both", func(b *state.Builder[string, string, *trec]) *state.Builder[string, string, *trec] {
		return b.State("supervising").InvokeActor("child", state.WithInvokeOnDone("childDone"), state.WithInvokeOnError("childErr")).
			Transition("idle").On("start").GoTo("supervising")
	}, "")
	zzFlipRun(t, "invokeErrOnly", func(b *state.Builder[string, string, *trec]) *state.Builder[string, string, *trec] {
		return b.State("supervising").InvokeActor("child", state.WithInvokeOnError("childErr")).
			Transition("idle").On("start").GoTo("supervising")
	}, "")
	zzFlipRun(t, "spawnErrOnly", func(b *state.Builder[string, string, *trec]) *state.Builder[string, string, *trec] {
		return b.State("supervising").
			Transition("idle").On("start").GoTo("supervising").Spawn("child", "kid", state.WithSpawnOnError("childErr"))
	}, "kid")
}

Run: go test -run TestZZFlip -v ./state

…JSON, and retry a settle on a finished actor

The re-review's blocker and its two mediums, on the declared-outcome
flags and the abort a delivery can no longer recover through stepping.

An older producer's JSON — a machine serialized before
Invocation.HasOnDone / HasOnError existed, or a SpawnActor effect
payload from before HasDone / HasError — never wrote the flags, so a
reload decoded every declared outcome as unset and the invoked actor's
success settled as the fire-and-forget no-op an outcome nothing
declared is: the declared onDone was lost. The loads now back-fill
each flag for an outcome whose key is absent and whose event is
present and non-zero — an older producer set the event only when it
declared it — so a reloaded definition keeps the outcomes it declared,
an unset outcome (the zero event) still routes nothing, and a new
producer's serialization round-trips byte-identically, flags, goldens
and TestRoundTrip_Identity unchanged. The Invocation test is typed and
exact; the SpawnActor effect's field is type-erased, so its zero test
is on the decoded value's own type — exact for the scalar events a
wire form distinguishes — and a composite event's declared outcomes
reload from the typed IR instead of an aged payload. The CHANGELOG's
sentence on pre-flags serializations now says all this.

A delivery or Tick to a running actor whose machine is already final —
an actor a settle's transform aborted left it that way — stepped the
machine anyway, firing the delivered event into the final state, which
failed as "state is final" and settled the actor as a failure through
onError (or an escalation): the actor's completed outcome was misrouted
as a crash. It now retries settling the final outcome instead, through
the same ownership path as any settle — the optional finalActor
interface the standard actorAdapter implements reports the final
machine — so the transform runs again, an abort is reported again to
the WithSettleAbortObserver, and once the transform stops aborting a
later delivery or Tick lands the good output through onDone. The retry
runs with an empty mailbox too, so a bare Tick settles an outcome a
delivery's abort left unsettled. Nothing is misrouted through onError.
Durable is unaffected: its live deliveries drive the same settle they
always did, so the journal records the same entries, and its replay
never delivers to an actor. The Deliver, Tick and WithSettleTransform
docs and the CHANGELOG say so, and the stale claim that an abort is
never recoverable through Deliver is gone. The WithSettleAbortObserver
doc's backwards sentence is fixed too: observe runs inside settle's
abort branch, before the abort reaches any caller, on every path,
while the settle still owns the actor.

Every behavioral test is red on the parent commit: the lost onDone,
from the IR and from an aged effect payload, the misrouted retry
through onError, and the empty Tick that left the outcome unsettled;
the byte-identity and unset-outcome tests pin what the back-fill must
not disturb.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
@reka18

reka18 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Done: every finding in both reviews is fixed, each with a test that failed at 681f0ef, including your TestZZ1-3 probes. The stale docs/src/content/docs/durable/overview.md:168 is updated (add67af). The new API and design calls are in the updated decisions comment.

@reka18

reka18 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Decisions for Temple to ratify (after your reviews)

These are new calls since the first decisions comment. Each is a suggestion for you to confirm or change.

  1. Journal the service settle first. When an actor abort lands in a service's step, the service result and the parent fires that applied are recorded before the Handle fails. So a ServiceFn never runs twice, and only the actor reruns.
  2. WithSettleAbortObserver is new state API. You suggested an observer. It's modeled on WithParentFireObserver and reports every abort on every path, carrying a SettleAbort[E] with the actor id, the event and the abort error.
  3. Explicit invoke flags. Invocation.HasOnDone/HasOnError (additive omitempty IR fields) and SpawnActor.HasDone/HasError, following your SpawnActor flag suggestion. An older machine's JSON back-fills them from a declared outcome.
  4. One settle owns the actor. This goes past a done recheck, so a losing concurrent settle never reports a false abort. The ServiceRunner tolerates the same window today, and bringing it to parity could be a follow-up.
  5. A finished but running actor retries its settle on the next delivery or Tick, instead of stepping a final machine.
  6. Issue state: an InvokeActor with no onError fires the zero event at the parent instead of escalating #250: the routing flags let two of its skipped probes pass, so they're unskipped. One case stays skipped, with its reason narrowed. I'll note it on state: an InvokeActor with no onError fires the zero event at the parent instead of escalating #250 after merge.

GO-2026-6974 in go.opentelemetry.io/otel/trace is fixed in v1.47.0.
The vulnerability scan fails on sink/gcppubsub, which reaches it through
pubsub.Publisher.Publish. Bump otel, metric and trace (and sdk where
used) to v1.47.0 in every module that pins them, then go mod tidy.
govulncheck is clean in all 20 modules.

Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
Signed-off-by: Ray Karnes <ray.karnes@stablekernel.com>
@reka18
reka18 merged commit 27ad55e into main Nov 24, 2026
112 checks passed
@reka18
reka18 deleted the fix/durable-actor-outcome-replay branch November 24, 2026 19:29
@reka18

reka18 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Done: your probe passes on main, and in both one-sided wirings the original error now escalates. The InvokeActor path is now pinned alongside Spawn in TestWithSettleTransform_ARewrittenFailureNothingRoutesEscalates, in #270 (66c47b2). Both rows failed at 681f0ef.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

confirmed:api-compatibility ACR clean: api-compatibility confirmed:concurrency-discipline ACR clean: concurrency-discipline confirmed:correctness ACR clean: correctness confirmed:human-readability ACR clean: human-readability confirmed:missed-context ACR clean: missed-context confirmed:probes ACR: the probes lens's latest round found no blocker confirmed:regression-safety ACR clean: regression-safety confirmed:replay-determinism ACR clean: replay-determinism ready All ACR dimensions confirmed - clear to merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

durable: an actor's done data and errors replay differently from the live run

2 participants